$(function () {
    $(".rule-single-checkbox").ruleSingleCheckbox();
	$('.am-back').click(function(){
		history.go(-1);
	});
	$(document).on("click",".imagelist .img-left",function(){
		var $li=$(this).parent().parent();
		var $pre=$li.prev("li");
		$pre.insertAfter($li)
	})
	$(document).on("click",".imagelist .img-right",function(){
		var $li=$(this).parent().parent();
		var $next=$li.next("li");
		$next.insertBefore($li);
	});
	$(document).on("click",".imagelist .img-del",function(){
		$(this).parent().parent().remove();
	});
	$(".fm-choose-ad").click(function(){
		var name=$(this).attr("data-name");
		var url=$(this).attr("data-url");
		var type=$(this).attr("data-type");
		var multiple=$(this).attr("data-multiple");
		var d=dialog({
			title:'附件选择',
			content:'<iframe id="picdata" src="'+url+'" scrolling="auto" frameborder="0" width="800" height="400"></iframe>',
			ok:function()
			{
				var val=$('#list',document.getElementById('picdata').contentWindow.document).find(".hover");
				if(val.length==0)
				{
					toastr.error('请选择附件');
					return false;
				}
				else
				{
					if(multiple==0)
					{
						$("#"+name).val(val.attr("data-url"));
					}
					else
					{
						val.each(function(){
							var url=$(this).attr("data-url");
							var num=1;
							$("#list_"+name+" li").each(function()
							{
								var maxnum=parseInt($(this).attr("num"));
								if(maxnum>=num)
								{
									num=maxnum+1;
								}
							});
							var html='';
							html+='<li num="'+num+'">';
							html+='	<div class="preview">';
							html+='		<input type="hidden" name="'+name+'['+num+'][image]" value="'+url+'">';
							html+='		<img src="'+url+'" />';
							html+='	</div>';
							html+='	<div class="intro">';
							html+='		<textarea name="'+name+'['+num+'][desc]" placeholder="请输入描述..."></textarea>';
							html+='	</div>';
							html+='	<div class="intro">';
							html+='		<textarea name="'+name+'['+num+'][url]" placeholder="请输入链接网址..."></textarea>';
							html+='	</div>';
							html+='	<div class="action"><a href="javascript:;" class="img-left"><i class="am-icon-angle-double-left am-icon-fw"></i>左移</a><a href="javascript:;" class="img-right"><i class="am-icon-angle-double-right am-icon-fw"></i>右移</a><a href="javascript:;" class="img-del"><i class="am-icon-close am-icon-fw"></i>删除</a></div>';
							html+='</li>';
							$("#list_"+name).append(html);
						})
						
					}
					d.remove();
					d.close();
				}
				return false;
			},
			okValue:'确定',
		}).showModal();
	});
	template_click();
	pic_preview();
	FmChoose();
	$("#select_master").click(function(){
		var config=$(this).attr("data-name");
		var url=$(this).attr("data-url");
		dialog({
			title:"素材选择",
			content:"<iframe src='"+url+"' width='950' height='500' frameborder='0' id='masterlist'></iframe>",
			padding:'10px',
			ok:function(){
				var id=$('#filelist',document.getElementById('masterlist').contentWindow.document).html();
				var html=$('#master_box',document.getElementById('masterlist').contentWindow.document).html();
				if(id!=null)
				{
					$("input[name="+config+"]").attr("value",id);
					$(".master_box").html(html);
					
				}
				},
			okValue:'确定',
			}).showModal();
	});
	$(".editor_savepic").click(function(){
		var name=$(this).attr("data-name");
		var url=$(this).attr("data-url");
		var ue=UE.getEditor(name);
		var data=ue.getContent();
		var that=this;
		$(this).val("处理中...");
		$.ajax({
			url:url,
			type:"post",
			data:"content="+encodeURIComponent(data),
			error:function(){alert(e.responseText)},
			success:function(d)
			{
				console.log(d);
				ue.setContent(d);
				$(that).val("处理完成");
				setTimeout(function(){$(that).val("保存编辑器中外部图片")},3000)
			}
		});
	});
})

//全选取消

function checkAll(chkobj) {
    if ($('label[for=ChannelID_1]').text() == "全选") {
        $('label[for=ChannelID_1]').text("取消");
        $("input[name=ChannelID]").prop("checked", true);
    } else {       
        $('label[for=ChannelID_1]').text("全选");
        $("input[name=ChannelID]").prop("checked", false);
    }
}
function jsprint(msgtitle, url, callback) {
    var d = dialog({ content: msgtitle }).show();
    setTimeout(function () {
        d.close().remove();
    }, 2000);
    if (url == "back") {
        frames["mainframe"].history.back(-1);
    } else if (url != "") {
        frames["mainframe"].location.href = url;
    }
    //执行回调函数
    if (arguments.length == 3) {
        callback();
    }
}

function checkall(form) {
    for (var i = 0; i < form.elements.length; i++) {
        var e = form.elements[i];
        if (e.Name != "chkall")
            e.checked = form.chkall.checked;
    }
}

function template_click(i) {
    if (typeof i == 'undefined') { i = ''; }
    $(".template"+i).click(function(){
        var name=$(this).attr("data-name");
        var url=$(this).attr("data-url");
        var d=dialog({
            title:'模板选择',
            content:'<iframe id="treedata" src="'+url+'" scrolling="auto" frameborder="0" width="650" height="350"></iframe>',
            ok:function()
            {
                var val=$('#go',document.getElementById('treedata').contentWindow.document).val();
                if(val=='')
                {
                    toastr.error('请选择模板');
                    return false;
                }
                else
                {
                    $("#"+name).val(val);
                    d.remove();
                    d.close();
                }
                return false;
            },
            okValue:'确定',
        }).showModal();
    });
}
function pic_preview(){
    $(".pic-preview").click(function () {
        var name = $(this).attr("data-name");
        if ($("#" + name).val() == '') {
            toastr.error("没有图片可预览");
        }
        else {
            layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                content: '<img src="' + $("#" + name).val() + '" style="max-width:360px;">'
            });
        }
    });
}

function FmChoose(i) {
    if (typeof i == 'undefined') { i = ''; }
    $(".fm-choose"+i).click(function(){
        var name=$(this).attr("data-name");
        var url=$(this).attr("data-url");
        var type=$(this).attr("data-type");
        var multiple=$(this).attr("data-multiple");
        var placeholer=$(this).attr("data-replace");
        var d=dialog({
            title:'模板选择',
            content:'<iframe id="picdata" src="'+url+'" scrolling="auto" frameborder="0" width="800" height="400"></iframe>',
            ok:function()
            {
                var val = $('#list', document.getElementById('picdata').contentWindow.document).find(".hover");
                
                if(val.length==0)
                {
                    toastr.error('请选择模板');
                    return false;
                }
                else
                {
                    if(multiple==0)
                    {
                        $("#" + name).val(val.attr("data-url"));					    
                        if(placeholer!='undefined')
                        {
                            $("."+placeholer).html('<img src='+val.attr("data-img")+'><p><pre>'+val.attr("title")+'</pre></p>');
                        }
                    }
                    else
                    {
                        val.each(function(){
                            var url=$(this).attr("data-url");
                            var num=1;
                            $("#list_"+name+" li").each(function()
                            {
                                var maxnum=parseInt($(this).attr("num"));
                                if (maxnum>=num)
                                {
                                    num=maxnum+1;
                                }
                            });
                            var html='';
                            html+='<li num="'+num+'">';
                            html+='	<div class="preview">';
                            html+='		<input type="hidden" name="'+name+'['+num+'][image]" value="'+url+'">';
                            html+='		<img src="'+url+'" />';
                            html+='	</div>';
                            html+='	<div class="intro">';
                            html+='		<textarea name="'+name+'['+num+'][desc]" placeholder="图片描述..."></textarea>';
                            html+='	</div>';
                            html+='	<div class="action"><a href="javascript:;" class="img-left"><i class="am-icon-angle-double-left am-icon-fw"></i>左移</a><a href="javascript:;" class="img-right"><i class="am-icon-angle-double-right am-icon-fw"></i>右移</a><a href="javascript:;" class="img-del"><i class="am-icon-close am-icon-fw"></i>删除</a></div>';
                            html+='</li>';
                            $("#list_"+name).append(html);
                        })
						
                    }
                    d.remove();
                    d.close();
                }
                return false;
            },
            okValue:'确定',
        }).showModal();
    });
}
function delAttachNode(obj) {
    $(obj).parent().remove();
}
function delAttachNode2(obj) {
    $(obj).parent().parent().parent().remove();
}
function delAttachNode1(obj) {
    $(obj).parent().parent().remove();
}
$(function () {
    // $('.fm-addimg').
    $(document).on('click', '.fm-addimg', function () {
        var data_id = $(this).siblings(".photo-list").attr("data-id");
        var _this = $(this).siblings(".photo-list").children("ul");
        var url = $(this).attr("data-url");
        var d = dialog({
            title: '插入远程图片',
            content: '<iframe id="imagesdata" src="' + url + '" scrolling="auto" frameborder="0" width="450" height="150"></iframe>',
            ok: function () {
                var val = $('#addimg', document.getElementById('imagesdata').contentWindow.document).val();
                if (val == '') {
                    toastr.error('请输入图片地址');
                    return false;
                }
                else {
                    var valarr = val.split('|');
                    var newLi = '';
                    for (var i = 0; i < valarr.length; i++) {
                         newLi += '<li>'
                     + '<input type="hidden" name="ImgLink' + data_id + '" value="' + valarr[i] + '" />'
                       + '<div class="img-box" onclick="setFocusImg(this);">'
                     + '<img src="' + valarr[i] + '" bigsrc="' + val[i] + '" />'
                     + '</div>'
                    + '<a href="javascript:;" class="img-left"><i class="am-icon-angle-double-left am-icon-fw"></i>左移</a><a href="javascript:;" class="img-right"><i class="am-icon-angle-double-right am-icon-fw"></i>右移</a>'
                     + '<a href="javascript:;" onclick="delImg(this);">删除</a>'
                     + '</li>';
                    }
                                      
                    _this.append(newLi);
                    d.remove();
                    d.close();
                }
                return false;
            },
            okValue: '插入',
        }).showModal();
    })
})
function getDefSpeechStyle(path, i ,_this) {
    if (typeof i == 'undefined') { i = 0 }
    var _data_action = $(_this).attr("data-action");
   // console.log(_data_action)
    $.ajax({
        type: 'get',
        cache: false,
        dataType: 'json',
        url: '/tool/Api.aspx?action=getDefSpeechStyle&style='+encodeURIComponent(path),       
        error: function (e) { alert(e.responseText); },
        success: function (d) {                
            if (d.Success) {
                var Data = d.Data;
                window.console && window.console.log && window.console.log(Data);
                Data = JSON.parse(Data);              
                try {                    
                    var identifier = Data.identifier || '';
                    var bgcolor = Data.bgcolor || '';
                    var imglink = Data.imglink || '';
                    var weblink = Data.weblink || '';
                    var textcolor = Data.textcolor || '';
                    var words = Data.words || '';                   
                    var bgcolorArr = bgcolor.split("|"), imglinkArr = imglink.split("|"), weblinkArr = weblink.split("|"), textcolorArr = textcolor.split("|"), wordsArr = words.split("|");                    
                    if (i == 0) {                      
                        var _bgColorstr = '';
                        for (var j = 0; j < bgcolorArr.length; j++) {
                            _bgColorstr += "<li><input name=\"BgColor2\" type=\"text\" value=\"" + bgcolorArr[j] + "\" class=\"minicolors0 minicolors2\"/>" + delattachNodeDiv(j) + "</li>";
                        }
                        $('#am_bgcolor_list0').html(_bgColorstr);
                        minicolorsFuc('.minicolors2');
                        var _weblinkStr = "";
                        for (var j = 0; j < weblinkArr.length; j++) {
                            _weblinkStr += "<li><input name=\"WebLink2\" type=\"text\" size=\"50\" value=\"" + weblinkArr[j] + "\" placeholder=\"请输入链接地址\" /><span class=\"am-margin-left input-tips\">如：http://www.baidu.com、tel:138000138000;</span>" + delattachNodeDiv(j) + "</li>";
                        }
                        $('#am-WebLink2-list').html(_weblinkStr);
                        var _wordsStr = "";
                        for (var j = 0; j < wordsArr.length; j++) {
                            textcolorArr[j] = textcolorArr[j] || '';
                            _wordsStr += "<li><input name=\"TextColor2\" type=\"text\" value=\"" + textcolorArr[j] + "\" class=\"minicolors minicolors0\"/> <input name=\"Words2\" type=\"text\" size=\"50\" value=\"" + stripscript(wordsArr[j]) + "\" placeholder=\"请输入文字内容\" /><span class=\"am-margin-left input-tips\">如：您好，有什么可以帮助的吗？</span>" + delattachNodeDiv(j) + "</li>";
                        }
                        $('#am-full-list').html(_wordsStr); minicolorsFuc('.minicolors0');
                        if (imglink!=''){
                            var _imglinkStr = "";
                            for (var j = 0; j < imglinkArr.length; j++) {
                                _imglinkStr += '<li>'
                                            + '<input type="hidden" name="ImgLink0" value="' + imglinkArr[j] + '" />'
                                            + '<div class="img-box" onclick="setFocusImg(this);">'
                                            + '<img src="' + imglinkArr[j] + '" bigsrc="' + imglinkArr[j] + '" />'
                                            + '</div>'
                                            + '<a href="javascript:;" class="img-left"><i class="am-icon-angle-double-left am-icon-fw"></i>左移</a><a href="javascript:;" class="img-right"><i class="am-icon-angle-double-right am-icon-fw"></i>右移</a>'
                                            + '<a href="javascript:;" onclick="delImg(this);">删除</a>'
                                            + '</li>';
                            }
                            $(".photo-list[data-id='0']").children("ul").html(_imglinkStr);
                        }
                        $('input[name=Ident2]').val(identifier);
                        $('input[name=FirstTime2]').val(3);
                        $('input[name=RelapseTime2]').val(25);
                        $('input[name=EachTime2]').val(10);
                    } else {
                        if (imglink != '') { 
                            var _imglinkStr = "";
                            for (var j = 0; j < imglinkArr.length; j++) {
                                _imglinkStr += '<li>'
                                            + '<input type="hidden" name="ImgLink'+ i +'" value="' + imglinkArr[j] + '" />'
                                            + '<div class="img-box" onclick="setFocusImg(this);">'
                                            + '<img src="' + imglinkArr[j] + '" bigsrc="' + imglinkArr[j] + '" />'
                                            + '</div>'
                                            + '<a href="javascript:;" class="img-left"><i class="am-icon-angle-double-left am-icon-fw"></i>左移</a><a href="javascript:;" class="img-right"><i class="am-icon-angle-double-right am-icon-fw"></i>右移</a>'
                                            + '<a href="javascript:;" onclick="delImg(this);">删除</a>'
                                            + '</li>';
                            }
                            $(".photo-list[data-id='" + i + "']").children("ul").html(_imglinkStr);
                        }
                        var _bgColorstr = '';
                        for (var j = 0; j < bgcolorArr.length; j++) {
                            if (i == 1 && _data_action!="edit") {
                                _bgColorstr += "<li><input name=\"BgColor\" type=\"text\" value=\"" + bgcolorArr[j] + "\" class=\"minicolors0 minicolors2\"/>" + delattachNodeDiv(j) + "</li>";
                            } else {
                                _bgColorstr += "<li><input name=\"BgColor-"+i+"\" type=\"text\" value=\"" + bgcolorArr[j] + "\" class=\"minicolors0 minicolors2\"/>" + delattachNodeDiv(j) + "</li>";
                            }
                           
                        }
                        if (i == 1 && _data_action != "edit") {
                            $('#am_bgcolor_list').html(_bgColorstr);
                        } else {
                            $('#am_bgcolor_list_' + i).html(_bgColorstr);
                        }                        
                        minicolorsFuc('.minicolors2');
                        var _weblinkStr = "";
                        for (var j = 0; j < weblinkArr.length; j++) {
                            _weblinkStr += "<li><input name=\"WebLink-"+i+"\" type=\"text\" size=\"50\" value=\"" + weblinkArr[j] + "\" placeholder=\"请输入链接地址\" /><span class=\"am-margin-left input-tips\">如：http://www.baidu.com、tel:138000138000;</span>" + delattachNodeDiv(j) + "</li>";
                        }
                        _this.parent().parent().parent().find('.am-WebLink-list').html(_weblinkStr);
                        
                        var _wordsStr = "";
                        for (var j = 0; j < wordsArr.length; j++) {
                            textcolorArr[j] = textcolorArr[j] || '';
                            if (i == 1 && _data_action != "edit") {
                                _wordsStr += "<li><input name=\"TextColor\" type=\"text\" value=\"" + textcolorArr[j] + "\" class=\"minicolors minicolors0\"/> <input name=\"Words\" type=\"text\" size=\"50\" value=\"" + stripscript(wordsArr[j]) + "\" placeholder=\"请输入文字内容\" /><span class=\"am-margin-left input-tips\">如：您好，有什么可以帮助的吗？</span>" + delattachNodeDiv(j) + "</li>";
                                
                            }
                            else {
                                _wordsStr += "<li><input name=\"TextColor-" + i + "\" type=\"text\" value=\"" + textcolorArr[j] + "\" class=\"minicolors minicolors0\"/> <input name=\"Words-" + i + "\" type=\"text\" size=\"50\" value=\"" + stripscript(wordsArr[j]) + "\" placeholder=\"请输入文字内容\" /><span class=\"am-margin-left input-tips\">如：您好，有什么可以帮助的吗？</span>" + delattachNodeDiv(j) + "</li>";
                            }
                        }
                        if (i == 1 && _data_action != "edit") {
                            $('#am-float-list').html(_wordsStr)
                        } else {
                            $('#am-float-list-' + i).html(_wordsStr);
                        }
                        minicolorsFuc('.minicolors0');                       
                        _this.parent().parent().parent().find('input[name=Ident]').val(identifier);
                        _this.parent().parent().parent().find('input[name=FirstTime]').val(3);
                        _this.parent().parent().parent().find('input[name=RelapseTime]').val(25);
                        _this.parent().parent().parent().find('input[name=EachTime]').val(10);
                    }
                    
                }
                catch (e) {
                    window.console && window.console.log && console.log(e);

                }
              
            }
        }
    })
}
$(document).on('click', '.style-preview', function () {
    var _this = $(this);
    var _data_id = _this.attr('data-id');
    var _data_name = _this.attr('data-name');
    var _data_name_val = $('#' + _data_name).val();
    toastr.options = { "positionClass": "toast-bottom-center", "timeOut": "3000", "onclick": null, showMethod: "slideDown", hideMethod: "slideUp" };    
    if (_data_name_val == '') {
        toastr.error('请选择风格模板!');
        return false;
    }
    layer.confirm(
            '确定要恢复默认吗？确定以下修改将不能恢复！',
            {
                btn: ['确定', '取消']
            }, function () {
                layer.closeAll();
                getDefSpeechStyle(_data_name_val, _data_id, _this);
            }
            , function () {

            });  
})
function delattachNodeDiv(i) {
    if (i > 0) return "<div class=\"am-icon-trash\" onclick=\"delAttachNode(this);\"></div>";
    return "";
}
function minicolorsFuc(color) {
    $(color).minicolors({
        control: $(this).attr('am-data-control') || 'hue',
        defaultValue: $(this).attr('data-defaultValue') || '',
        inline: $(this).attr('data-inline') === 'true',
        letterCase: $(this).attr('data-letterCase') || 'lowercase',
        opacity: $(this).attr('data-opacity'),
        position: $(this).attr('data-position') || 'bottom left',
        change: function (hex, opacity) {
            if (!hex) return;
            if (opacity) hex += ', ' + opacity;
            try {
            } catch (e) { }
        },
        theme: 'amazeui'
    });
}
//复选框
$.fn.ruleSingleCheckbox = function () {
    var singleCheckbox = function (parentObj) {
        //查找复选框
        var checkObj = parentObj.children('input:checkbox').eq(0);
        //防止重复初始化，删除a标签
        parentObj.children('a').remove();
        //隐藏原生复选框
        parentObj.children().hide();
        //添加元素及样式
        var newObj = $('<a href="javascript:;">'
		+ '<i class="off">否</i>'
		+ '<i class="on">是</i>'
		+ '</a>').prependTo(parentObj);
        parentObj.addClass("single-checkbox");
        //判断是否选中
        if (checkObj.prop("checked") == true) {
            newObj.addClass("selected");
        }
        //检查控件是否启用
        if (checkObj.prop("disabled") == true) {
            newObj.css("cursor", "default");
            return;
        }
        //绑定事件
        newObj.click(function () {
            if ($(this).hasClass("selected")) {
                $(this).removeClass("selected");
            } else {
                $(this).addClass("selected");
            }
            checkObj.trigger("click"); //触发对应的checkbox的click事件
        });
        //绑定反监听事件
        checkObj.on('click', function () {
            if ($(this).prop("checked") == true && !newObj.hasClass("selected")) {
                newObj.addClass("selected");
            } else if ($(this).prop("checked") == false && newObj.hasClass("selected")) {
                newObj.removeClass("selected");
            }
        });
    };
    return $(this).each(function () {
        singleCheckbox($(this));
    });
};

function stripscript(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    return s;
}
// 转为unicode 编码
function encodeUnicode(str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
        res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
}

// 解码
function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
}

function checkNumber(e) {
    var keynum = window.event ? e.keyCode : e.which;
    if ((48 <= keynum && keynum <= 57) || (96 <= keynum && keynum <= 105) || keynum == 8) {
        return true;
    } else {
        return false;
    }
}